﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace IFT.Classes
{
  class CombatLine : IEnumerator, IEnumerable
  {
    private List<Unit> m_field  = new List<Unit>();
    private Player m_owner      = null;
    private UnitType m_type     = UnitType.MinUnitFieldType;
    protected int m_position    = -1;

    #region EnumeratorDefines
    public IEnumerator GetEnumerator()
    {
      return (IEnumerator)this;
    }

    public bool MoveNext()
    {
      m_position++;
      return (m_position < m_field.Count);
    }

    public void Reset()
    {
      m_position = 0;
    }

    public Object Current
    {
      get { return m_field[m_position]; }
    }
    #endregion EnumeratorDefines
    #region PlayerPropertys
    public Player Owner
    {
      get { return m_owner; }
      set { m_owner = (Player)value; }
    }

    public UnitType Type
    {
      get { return m_type; }
      set { m_type = (UnitType)value; }
    }
    #endregion PlayerPropertys

    public CombatLine() { }

    public CombatLine(Player Owner, UnitType UType)
    {
      m_owner     = Owner;
      m_type      = UType;

      for (int i = 0; i < m_owner.BattleField.GetMaxSlots(m_type); i++)
        m_field.Add(new Unit(m_owner));
    }

    public UnitDamage GetLog()
    {
      UnitDamage damage = new UnitDamage();

      foreach (Unit unit in m_field)
        unit.GetLog(ref damage);

      return damage;
    }

    public bool HasUnit(int unitId)
    {
      foreach (Unit unit in m_field)
      {
        if (unit.IsLoaded() && unit.Info.ID == unitId && unit.Count > 0)
          return true;
      }

      return false;
    }

    public bool HasUnit(UnitType unitType)
    {
      foreach (Unit unit in m_field)
      {
        if (unit.IsLoaded() && unit.IsType(unitType) && unit.Count > 0)
          return true;
      }

      return false;
    }

    public void FillLine()
    {
      XMLUnit NextUnit = m_owner.GetNextUnitOnReserve(m_type, true);

      if (NextUnit != null)
      {
        foreach (Unit unit in m_field)
        {
          if (!unit.IsLoaded() || unit.Equals(NextUnit))
          {
            unit.LoadUnit(NextUnit);
            unit.PushToField();

            if (!HasUnit(NextUnit.ID))
              NextUnit = m_owner.GetNextUnitOnReserve(m_type, true);
          }
        }
      }
    }
  }
}
